<template>
  <div class="tab-bar">
    <template v-for="(item, index) in tabbarData" :key="item.text">
      <div 
          class="tab-bar-item"
          :class="{active: currentIndex === index}"
          @click="itemClick(index, item)">
        <img v-if="currentIndex !== index" :src="getAssetURL(item.image)" alt="">
        <img v-else :src="getAssetURL(item.imageActive)" alt="">
        <span class="text">{{item.text}}</span>
      </div>
    </template>
  </div>
</template>

<script setup>
  import { ref, watch } from "vue";
  import { useRouter, useRoute } from "vue-router";

  import tabbarData from '@/assets/data/tabbar.js'
  import { getAssetURL } from '@/utils/load_assets.js'

  // 监听路由改变时，找到对应的索引，设置currentIndex
  const route = useRoute()
  const currentIndex = ref(0)

  watch(route, (newRoute) => {
    const index = tabbarData.findIndex(item => item.path === newRoute.path)
    if (index === -1) return
    currentIndex.value = index
  })

  // 点击item实现路由跳转
  const router = useRouter()
  const itemClick = (index, item) => {
    currentIndex.value = index
    router.push(item.path)
  }
</script>

<style lang="less" scoped>
  .tab-bar {
    position: fixed;
    background-color: #fff;
    bottom: 0;
    right: 0;
    left: 0;
    height: 50px;

    display: flex;

    border-top: solid 1px #f3f3f3;

    .tab-bar-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      &.active {
        color: var(--primary-color);
      }

      .text {
        font-size: 12px;
      }

      img {
        margin-top: 2px;
        width: 32px;
      }
    }
  }
</style>